package com.jyy.utils.dynamicdatasource.utils;

import com.alibaba.druid.pool.DruidDataSource;
import com.jyy.utils.dynamicdatasource.DynamicProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据源工具类
 *
 * @author jyy
 * @data 2025-01-14
 */
@Slf4j
public class DynamicDbUtil {

    /**
     * 获取数据源
     *
     * @param dbKey             数据源key
     * @param dynamicProperties 数据源配置对象
     * @return DruidDataSource
     */
    public static DruidDataSource getDbSourceByDbKey(final String dbKey, DynamicProperties dynamicProperties) {
        DruidDataSource dataSource = getJdbcDataSource(dbKey, dynamicProperties);
        log.info("-------------------创建数据库[ {} ]DB连接-------------------", dbKey);
        return dataSource;
    }

    /**
     * 获取数据源【最底层方法，不要随便调用】
     *
     * @param dbKey             数据源key
     * @param dynamicProperties 数据源配置对象
     */
    private static DruidDataSource getJdbcDataSource(final String dbKey, DynamicProperties dynamicProperties) {
        DruidDataSource dataSource = new DruidDataSource();
        String driverClassName = dynamicProperties.getDriverClassMame();
        String url = dynamicProperties.getJdbcUrl(dbKey);
        String dbUser = dynamicProperties.getUsername();
        String dbPassword = dynamicProperties.getPassword();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        //dataSource.setValidationQuery("SELECT 1 FROM DUAL");
        dataSource.setTestWhileIdle(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setBreakAfterAcquireFailure(true);
        dataSource.setConnectionErrorRetryAttempts(0);
        dataSource.setUsername(dbUser);
        dataSource.setMaxWait(60000);
        dataSource.setPassword(dbPassword);

        log.info("******************************************");
        log.info("*                                        *");
        log.info("*====[ {} ]=====Druid连接池已启用 ====*", driverClassName);
        log.info("*                                        *");
        log.info("******************************************");
        return dataSource;
    }

    /**
     * 关闭数据库连接池
     *
     * @param dbKey
     * @return
     */
    public static void closeDbKey(final String dbKey, DynamicProperties dynamicProperties) {
        DruidDataSource dataSource = getDbSourceByDbKey(dbKey, dynamicProperties);
        try {
            if (dataSource != null && !dataSource.isClosed()) {
                dataSource.getConnection().commit();
                dataSource.getConnection().close();
                dataSource.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    private static JdbcTemplate getJdbcTemplate(String dbKey, DynamicProperties dynamicProperties) {
        DruidDataSource dataSource = getDbSourceByDbKey(dbKey, dynamicProperties);
        return new JdbcTemplate(dataSource);
    }

    /**
     * 获取连接
     *
     * @param url
     * @param username
     * @param password
     * @param driverName
     * @return
     */
    public static Connection getConn(String url, String username, String password, String driverName) {
        Connection conn = null;
        try {
            Class.forName(driverName);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            throw new RuntimeException("无法连接，问题：" + e.getMessage(), e);
        }

        return conn;
    }

    /**
     * 关闭数据库连接
     *
     * @param
     */
    public static void closeConnection(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException("close connection failure", e);
        }
    }
}
